package com.leo.leetcode.s100;

/**
 *
 * @author xuexiaolei
 * @version 2017年11月17日
 */
public class T06ZigZagConversion {
    public static String convert(String s, int numRows) {
        if ("".equals(s) || s==null) return "";
        if (numRows == 0 || numRows == 1 || s.length() <= numRows) return s;

        char[] cs = s.toCharArray();
        char[][] r = new char[numRows][s.length()];//存放每行的字母
        char[] len = new char[numRows];//每个行的字母个数
        int i = 0, j = 0;//模拟当前的位置
        boolean down = true;//是否朝下走

        for (int k = 0; k < s.length(); k++) {
            char tmp = cs[k];
            r[i][len[i]] = tmp;
            len[i]++;
            if (down){
                if (i+1 < numRows){
                    i++;
                }else {
                    down = false;
                    j++;
                    i--;
                }
            }else{
                if (i-1 >= 0){
                    i--;
                    j++;
                }else {
                    down=true;
                    i++;
                }
            }
        }

        StringBuffer sb = new StringBuffer();
        for (int k = 0; k < len.length; k++) {
            for (int l = 0; l < len[k]; l++) {
                sb.append(r[k][l]);
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(convert("PAYPALISHIRING", 3));
    }
}
